package cn.com.dashihui.kit;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;

public class CommonKit {
	
	/**
	 * 判断当前请求是否是手持设备
	 * @param request
	 * @return
	 */
	public static boolean isHandDev(HttpServletRequest request){
		//\b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔),
		// 字符串在编译时会被转码一次,所以是 "\\b"
		// \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)
		String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i|windows (phone|ce)|blackberry|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp|laystation portable)|nokia|fennec|htc[-_]|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";  
		String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
		
		//移动设备正则匹配：手机端、平板
		Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
		Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);
		try{
			//获取ua，用来判断是否为移动端访问
			String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();
			if(null == userAgent){
			    userAgent = "";
			}
		    //匹配手机端
		    Matcher matcherPhone = phonePat.matcher(userAgent);
		    //匹配平板端
		    Matcher matcherTable = tablePat.matcher(userAgent);
		    return matcherPhone.find()||matcherTable.find();
		}catch(Exception e){}
		return false;
	}
	
	/**
	 * 生成指定位数的随机数字
	 */
	public static String buildRandomNum(int len){
		StringBuffer random = new StringBuffer(len);
		for(int i = 0; i < len; i++){
			random.append((int)(Math.random() * 10));
		}
		return random.toString();
	}
	/**
	 * 不会重复字符串
	 */
	public static String buildRandomString(){
	    Date date = new Date();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSS");
	     String  formDate =sdf.format(date);
	     String no = formDate.substring(10);
		return no.toString();
	}
	/**
	 * 判断当前请求是否为异步请求
	 */
	public static boolean isAjax(HttpServletRequest request){
		//当请求为异步AJAX请求时，比传统请求多了一个头信息X-Requested-With，可通过判断该参数是否存在以确定是否是异步请求
		String xRequestedWith = request.getHeader("X-Requested-With");
		return !StrKit.isBlank(xRequestedWith);
	}
	
	/**
	 * 获取UUID
	 */
	public static String getUUID(){
		String s = UUID.randomUUID().toString(); 
        //去掉“-”符号 
        return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24); 
	}
	
	private static final String UNKNOWN = "unknown";
	private static final String LOCALHOST = "0:0:0:0:0:0:0:1";
	/**
	 * 根据请求获取客户端真实ip
	 * @param request
	 * @return
	 */
	public static String getClientIp(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getHeader("HTTP_CLIENT_IP");		
		}
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getHeader("X_FORWARDED_FOR");		
		}
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
		}
		if(LOCALHOST.equals(ip)){
			return "127.0.0.1";
		}else{
			int index = ip.indexOf(" ");
			if(index >= 0){
				ip = ip.substring(0,index);
			}
			return ip;
		}
	}
	
	/**
	 * 密码加密
	 */
	public static String encryptPassword(String passwordStr){
		return DigestUtils.md5Hex(passwordStr);
	}
	
	/**
	 * 密码对比
	 */
	public static boolean passwordsMatch(String passwordStr, String encrypted){
		if(!StrKit.isBlank(passwordStr)&&!StrKit.isBlank(encrypted)){
			return encryptPassword(passwordStr).equalsIgnoreCase(encrypted);
		}
		return false;
	}
	/**
	 * 格式化当前日期
	 * @param format 时间样式（yyyy-MM-dd HH:mm:ss）
	 */
	public static String getFormatDate(String format){
		if(StrKit.isBlank(format)){
			format="yyyy-MM-dd HH:mm:ss";
		}
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}
	
	/**
	    * 获取一定长度的随机字符串
	    * @param length 指定字符串长度
	    * @return 一定长度的字符串
	    */
	   public static String getRandomStringByLength(int length) {
	       String base = "abcdefghijklmnopqrstuvwxyz0123456789";
	       Random random = new Random();
	       StringBuffer sb = new StringBuffer();
	       for (int i = 0; i < length; i++) {
	           int number = random.nextInt(base.length());
	           sb.append(base.charAt(number));
	       }
	       return sb.toString();
	   }
	   
	    /**
	     * 保存微信二维码
	     */
	    public static String saveWXQrcode(String qrcode_url, String ftpPath) throws Exception{
	    	String filePath = "";
	    	try {
				URL url = new URL(qrcode_url);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5 * 1000);
				InputStream input = conn.getInputStream();
				byte[] data = readInputStream(input);
				String imgPath = PathKit.getWebRootPath() + "/upload/" + System.currentTimeMillis() + ".jpg";
				File imageFile = new File(imgPath);
				//创建输出流 
		        FileOutputStream outStream = new FileOutputStream(imageFile);
		        //写入数据 
		        outStream.write(data);
		        //关闭输出流
		        outStream.close();
		        File file = new File(imgPath);
		        //获取文件，并上传至FTP根目录下，用UUID重命名
		        String fileName = file.getName();
		        String extension = fileName.substring(fileName.lastIndexOf("."));
		        String newFileName = CommonKit.getUUID();
		        FTPClientKit.upload(ftpPath, newFileName + extension, file);
		        filePath = ftpPath + newFileName + extension;
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
	    	return filePath;
	    }
	    /**
	     * 保存微信二维码 并返回二维码ftp地址以及二维码图片对象
	     */
	    public static Map<String,Object> returnWXQrcode(String qrcode_url, String ftpPath) throws Exception{
	    	Map<String,Object> map = new HashMap<String, Object>();
	    	String filePath = null;
	    	File file = null;
	    	try {
				URL url = new URL(qrcode_url);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5 * 1000);
				InputStream input = conn.getInputStream();
				byte[] data = readInputStream(input);
				String imgPath = PathKit.getWebRootPath() + "/upload/" + System.currentTimeMillis() + ".jpg";
				File imageFile = new File(imgPath);
				//创建输出流 
		        FileOutputStream outStream = new FileOutputStream(imageFile);
		        //写入数据 
		        outStream.write(data);
		        //关闭输出流
		        outStream.close();
		        //获取文件，并上传至FTP根目录下，用UUID重命名
		        file = new File(imgPath);
		        map.put("file", file);
		        String fileName = file.getName();
		        String extension = fileName.substring(fileName.lastIndexOf("."));
		        String newFileName = CommonKit.getUUID();
		        FTPClientKit.upload(ftpPath, newFileName + extension, file);
		        filePath = ftpPath + newFileName + extension;
		        map.put("qrcodePath", filePath);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
	    	return map;
	    }
	   
	    /**
	     * 
	     * @param inStream
	     * @return
	     * @throws Exception
	     */
	    public static byte[] readInputStream(InputStream inStream) throws Exception{  
	        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
	        //创建一个Buffer字符串  
	        byte[] buffer = new byte[1024];  
	        //每次读取的字符串长度，如果为-1，代表全部读取完毕  
	        int len = 0;  
	        //使用一个输入流从buffer里把数据读取出来  
	        while( (len=inStream.read(buffer)) != -1 ){  
	            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
	            outStream.write(buffer, 0, len);  
	        }  
	        //关闭输入流  
	        inStream.close();  
	        //把outStream里的数据写入内存  
	        return outStream.toByteArray();  
	    } 
	    /**
		 * 将入参strs以字符串split为分隔进行拼接
		 */
		public static String join(String split,String... strs){
			if(strs!=null&&strs.length!=0){
				StringBuffer sBuffer = new StringBuffer();
				for(String str : strs){
					sBuffer.append(str).append(split);
				}
				sBuffer.deleteCharAt(sBuffer.length()-1);
				return sBuffer.toString();
			}
			return null;
		}
		
		public static String join(String split,int... ints){
			if(ints!=null&&ints.length!=0){
				StringBuffer sBuffer = new StringBuffer();
				for(int str : ints){
					sBuffer.append(str).append(split);
				}
				sBuffer.deleteCharAt(sBuffer.length()-1);
				return sBuffer.toString();
			}
			return null;
		}
}
